<template>
  <div class="login-container">
    <!-- 左上角Logo -->
    <div class="header-logo">
      <img src="@/assets/login/logo.png" alt="Logo" class="logo" />
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 登录框 -->
      <div class="login-box">
        <!-- 登录框左侧 - 手机扫码 -->
        <div class="login-left">
          <h3 class="scan-title">手机扫码登录</h3>
          <div class="qr-code">
            <!-- 这里放置二维码图片，您可以替换为实际的二维码 -->
            <div class="qr-placeholder">
              <div class="qr-inner">
                <i class="el-icon-qrcode"></i>
                <p>请使用手机扫描二维码</p>
              </div>
            </div>
          </div>
          <p class="scan-tip">打开淘宝APP，点击右上角扫一扫</p>
        </div>

        <!-- 登录框右侧 - 表单登录 -->
        <div class="login-right">
          <!-- 登录方式切换 -->
          <div class="login-tabs">
            <div 
              class="tab-item" 
              :class="{ active: loginType === 'password' }"
              @click="loginType = 'password'"
            >
              密码登录
            </div>
            <div 
              class="tab-item" 
              :class="{ active: loginType === 'sms' }"
              @click="loginType = 'sms'"
            >
              短信登录
            </div>
          </div>

          <!-- 密码登录表单 -->
          <el-form
            v-if="loginType === 'password'"
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            class="login-form"
          >
            <el-form-item prop="account">
              <el-input
                v-model="passwordForm.account"
                placeholder="账号/邮箱/手机号"
                :prefix-icon="User"
                clearable
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="passwordForm.password"
                type="password"
                placeholder="请输入登录密码"
                :prefix-icon="Lock"
                show-password
                clearable
                @keyup.enter="handlePasswordLogin"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                class="login-button"
                @click="handlePasswordLogin"
                :loading="loading"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 短信登录表单 -->
          <el-form
            v-if="loginType === 'sms'"
            ref="smsFormRef"
            :model="smsForm"
            :rules="smsRules"
            class="login-form"
          >
            <el-form-item prop="phone">
              <el-input
                v-model="smsForm.phone"
                placeholder="请输入手机号"
                :prefix-icon="Phone"
                clearable
              >
                <template #prepend>
                  <el-select v-model="smsForm.countryCode" style="width: 80px">
                    <el-option label="+86" value="+86" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item prop="code">
              <el-input
                v-model="smsForm.code"
                placeholder="请输入验证码"
                clearable
                @keyup.enter="handleSmsLogin"
              >
                <template #append>
                  <el-button 
                    @click="sendSmsCode" 
                    :disabled="smsCountdown > 0"
                    type="text"
                  >
                    {{ smsCountdown > 0 ? `${smsCountdown}s后重发` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                class="login-button"
                @click="handleSmsLogin"
                :loading="loading"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 第三方登录 -->
          <div class="third-party-login">
            <div class="divider">
              <span>第三方登录</span>
            </div>
            <div class="social-buttons">
              <div class="social-btn weixin">
                <i class="social-icon">微信</i>
              </div>
              <div class="social-btn qq">
                <i class="social-icon">QQ</i>
              </div>

            </div>
          </div>

          <!-- 忘记密码和注册链接 -->
          <div class="login-links">
            <a href="#" class="link">忘记账号</a>
            <a href="#" class="link">免费注册</a>
          </div>

          <!-- 协议勾选 - 移动到登录框右侧 -->
          <div class="agreement">
            <el-checkbox v-model="agreeTerms">
              我已阅读并同意
              <a href="#" class="agreement-link">《用户协议》</a>
              和
              <a href="#" class="agreement-link">《隐私政策》</a>
            </el-checkbox>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Phone } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { AuthApi, type LoginDTO } from '@/api/auth'

const router = useRouter()

// 登录类型
const loginType = ref<'password' | 'sms'>('password')

// 加载状态
const loading = ref(false)

// 协议勾选
const agreeTerms = ref(false)

// 短信倒计时
const smsCountdown = ref(0)

// 表单引用
const passwordFormRef = ref()
const smsFormRef = ref()

// 密码登录表单
const passwordForm = reactive({
  account: '',
  password: ''
})

// 短信登录表单
const smsForm = reactive({
  countryCode: '+86',
  phone: '',
  code: ''
})

// 密码登录验证规则
const passwordRules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 短信登录验证规则
const smsRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 密码登录
const handlePasswordLogin = async () => {
  if (!agreeTerms.value) {
    ElMessage.warning('请先阅读并同意用户协议和隐私政策')
    return
  }

  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return

    loading.value = true
    
    const loginData: LoginDTO = {
      account: passwordForm.account,
      password: passwordForm.password
    }
    //发起登录请求
    const response = await AuthApi.accountLogin(loginData)
    
    if (response.code === 0) {
      const { accessToken, userInfo } = response.data
      localStorage.setItem('token', accessToken)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      ElMessage.success('登录成功')
      setTimeout(() => {
        router.push('/index')
      }, 1000)
    }
  } catch (error) {
    console.error('登录失败:', error)
  } finally {
    loading.value = false
  }
}

// 短信登录
const handleSmsLogin = async () => {
  if (!agreeTerms.value) {
    ElMessage.warning('请先阅读并同意用户协议和隐私政策')
    return
  }

  try {
    const valid = await smsFormRef.value.validate()
    if (!valid) return

    loading.value = true
    
    // 这里应该调用短信登录API，暂时使用模拟
    const response = await AuthApi.verifyCodeLogin({
      phone: smsForm.phone,
      code: smsForm.code
    })
    // 校验登录状态码
    if(response.code ===0){
      // 获取token和用户信息
      const { accessToken, userInfo } = response.data
      // 存储token和用户信息到本地存储
      localStorage.setItem('token',accessToken)
      localStorage.setItem('userInfo',JSON.stringify(userInfo))
      // 显示成功消息
      ElMessage.success('登录成功')
      // 延迟跳转到首页
      setTimeout(() => {
        router.push('/index')
      }, 2000)
    }
  } catch (error) {
    console.error('短信登录失败:', error)
  } finally {
    loading.value = false
  }
}

// 发送短信验证码
const sendSmsCode = async () => {
  if (!smsForm.phone) {
    ElMessage.warning('请先输入手机号')
    return
  }
  
  if (!/^1[3-9]\d{9}$/.test(smsForm.phone)) {
    ElMessage.warning('请输入正确的手机号')
    return
  }

  // 开始倒计时
  smsCountdown.value = 60
  const timer = setInterval(() => {
    smsCountdown.value--
    if (smsCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)

  try {
    // 发送短信验证码API
    const response = await AuthApi.getVerifyCode(smsForm.phone)
    if(response.code === 0){
       ElMessage.success('验证码发送成功')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    smsCountdown.value = 0
    clearInterval(timer)
  }
}
</script>

<style scoped>
/* 登录页面主容器 */
.login-container {
  /* min-height: 100vh; */
  height: 900px;
  background-color: #F0EFF2;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

/* 左上角Logo区域 */
.header-logo {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
}

/* Logo图片样式 */
.logo {
  height: 50px;
  width: auto;
}

/* 主要内容区域容器 */
.main-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  width: 100%;
  max-width: 900px;
  padding: 20px;
}

/* 登录框主体 */
.login-box {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  width: 100%;
  max-width: 800px;
  height: auto;
  max-height: calc(100vh - 120px);
}

/* 登录框左侧扫码区域 */
.login-left {
  flex: 1;
  background: #f8f9fa;
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  min-height: 400px;
}

/* 扫码登录标题 */
.scan-title {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
  font-weight: 500;
}

/* 二维码容器 */
.qr-code {
  margin-bottom: 15px;
}

/* 二维码占位符 */
.qr-placeholder {
  width: 180px;
  height: 180px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
}

/* 二维码内部内容 */
.qr-inner {
  text-align: center;
  color: #999;
}

/* 二维码图标 */
.qr-inner i {
  font-size: 40px;
  margin-bottom: 8px;
  display: block;
}

/* 二维码说明文字 */
.qr-inner p {
  margin: 0;
  font-size: 12px;
}

/* 扫码提示文字 */
.scan-tip {
  color: #666;
  font-size: 12px;
  margin: 0;
}

/* 登录框右侧表单区域 */
.login-right {
  flex: 1;
  padding: 30px;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

/* 登录方式切换标签 */
.login-tabs {
  display: flex;
  margin-bottom: 25px;
  border-bottom: 1px solid #eee;
}

/* 单个标签项 */
.tab-item {
  padding: 10px 20px;
  cursor: pointer;
  color: #666;
  font-size: 16px;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

/* 激活状态的标签 */
.tab-item.active {
  color: #ff6900;
  border-bottom-color: #ff6900;
  font-weight: 500;
}

/* 标签悬停效果 */
.tab-item:hover {
  color: #ff6900;
}

/* 登录表单容器 */
.login-form {
  flex: 1;
}

/* 表单项间距 */
.login-form .el-form-item {
  margin-bottom: 18px;
}

/* 登录按钮样式 */
.login-button {
  width: 100%;
  height: 42px;
  font-size: 16px;
  background: #ff6900;
  border-color: #ff6900;
}

/* 登录按钮悬停效果 */
.login-button:hover {
  background: #e55a00;
  border-color: #e55a00;
}

/* 第三方登录区域 */
.third-party-login {
  margin: 25px 0 20px 0;
}

/* 分割线容器 */
.divider {
  text-align: center;
  position: relative;
  margin-bottom: 15px;
}

/* 分割线样式 */
.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #eee;
}

/* 分割线文字 */
.divider span {
  background: white;
  padding: 0 15px;
  color: #999;
  font-size: 14px;
}

/* 社交登录按钮组 */
.social-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
}

/* 社交登录按钮基础样式 */
.social-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

/* 微信登录按钮 */
.social-btn.weixin {
  background: #1aad19;
  color: white;
}

/* QQ登录按钮 */
.social-btn.qq {
  background: #12b7f5;
  color: white;
}

/* 微博登录按钮 */
.social-btn.weibo {
  background: #e6162d;
  color: white;
}

/* 社交按钮悬停效果 */
.social-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 社交按钮图标 */
.social-icon {
  font-size: 16px;
  font-weight: bold;
}

/* 登录相关链接容器 */
.login-links {
  display: flex;
  justify-content: space-between;
  margin: 15px 0;
}

/* 链接样式 */
.link {
  color: #666;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.3s;
}

/* 链接悬停效果 */
.link:hover {
  color: #ff6900;
}

/* 协议勾选区域 */
.agreement {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

/* 协议链接样式 */
.agreement-link {
  color: #ff6900;
  text-decoration: none;
}

/* 协议链接悬停效果 */
.agreement-link:hover {
  text-decoration: underline;
}

</style>